package com.android.clinic.app.http.base;

import com.android.clinic.app.http.exception.ExceptionEnum;
import com.android.clinic.app.utils.Constants;
import com.google.gson.JsonParseException;
import com.jakewharton.retrofit2.adapter.rxjava2.HttpException;

import org.json.JSONException;

import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.UnknownHostException;
import java.text.ParseException;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * Created by cheng on 2018/2/7.
 */
public abstract class BaseObserver<T> implements Observer<BaseResponse<T>> {

    /*网络错误*/
    private static final int CONNECT_ERROR = 0x1;
    /*http错误*/
    private static final int CONNECT_TIMEOUT = 0x2;
    /*服务器异常*/
    private static final int BAD_NETWORK = 0x3;
    /*数据解析错误*/
    private static final int PARSE_ERROR = 0x4;
    /*未知错误*/
    private static final int UNKNOWN_ERROR = 0x5;

    @Override
    public void onSubscribe(@NonNull Disposable d) {

    }

    @Override
    public void onNext(@NonNull BaseResponse<T> response) {
        if (Constants.HTTP_SUCCESS.equals(response.getCode())) {
            onSuccess(response.getData());
        } else if (Constants.HTTP_ERROR.equals(response.getCode())) {
            onFailure(response.getMessage());
        } else {
            onFailure(ExceptionEnum.getMessage(UNKNOWN_ERROR));
        }
    }

    @Override
    public void onError(@NonNull Throwable e) {
        if (e instanceof HttpException) {
            onFailure(ExceptionEnum.getMessage(CONNECT_ERROR));
        } else if (e instanceof ConnectException
                || e instanceof UnknownHostException) {
            onFailure(ExceptionEnum.getMessage(CONNECT_TIMEOUT));
        } else if (e instanceof InterruptedIOException) {
            onFailure(ExceptionEnum.getMessage(BAD_NETWORK));
        } else if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException) {
            onFailure(ExceptionEnum.getMessage(PARSE_ERROR));
        } else {
            if (e.getMessage().contains("504")) {
                onFailure(ExceptionEnum.getMessage(CONNECT_ERROR));
            } else {
                onFailure(e.getMessage());
            }
        }
    }

    @Override
    public void onComplete() {

    }

    /**
     * 根据具体的API业务逻辑去重写onSuccess法
     * @param t
     */
    public abstract void onSuccess(T t);

    /**
     * 根据具体的API业务逻辑去重写onError法
     * @param message
     */
    public abstract void onFailure(String message);
}
